package cn.dai.advice;

import cn.dai.util.TokenUtil;
import cn.dai.exception.TokenAuthException;
import cn.dai.pojo.ReturnCode;
import cn.dai.pojo.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author daijiyong
 */
@Slf4j
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {

    /**
     * 权限认证的拦截操作.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws TokenAuthException {
        log.info("=======进入拦截器========");
        // 如果不是映射到方法直接通过,可以访问资源.
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        //为空就返回错误
        String token = httpServletRequest.getHeader(TokenUtil.REQUEST_HEADER_TOKEN_KEY);
        if (null == token || "".equals(token.trim())) {
            throw new TokenAuthException(ReturnCode.INVALID_TOKEN);
        }
        TokenVo tokenVo = TokenUtil.parseToken(token);
        long timeOfUse = System.currentTimeMillis() - tokenVo.getTimestamp();
        //1.判断 token 是否过期
        //年轻 token
        /*if (timeOfUse < TokenUtil.youngToken) {
            log.info("年轻 token");
        }*/
        //老年 token 就刷新 token
        if (timeOfUse >= TokenUtil.youngToken && timeOfUse < TokenUtil.oldToken) {
            TokenUtil.getToken(tokenVo);
            httpServletResponse.setHeader(TokenUtil.REQUEST_HEADER_TOKEN_KEY, tokenVo.getToken());
            httpServletResponse.setHeader(TokenUtil.REQUEST_HEADER_EXPIRES_KEY, String.valueOf(tokenVo.getTimestamp() + TokenUtil.oldToken));
        }
        //过期 token 就返回 token 无效.
        else {
            throw new TokenAuthException(ReturnCode.INVALID_TOKEN);
        }
        return false;
    }
}
